<template>
  <div class="app-container">
    <el-row :gutter="18">
      <el-col :span="16">
        <el-descriptions
          :title="filterOrderStatus(orderInfo ? orderInfo.orderStatus : '')"
          :column="1"
          class="out-border mb10"
        >
          <!-- 已下单待支付 -->
          <template slot="extra" v-if="orderInfo && orderInfo.orderStatus == 'WAIT_PAY'">
            <div style="display: flex; justify-content: flex-end">
              <el-button size="small" type="primary" @click="onGoPay">去支付</el-button>
              <el-button size="small" type="danger" @click="onCancelOrder">取消订单</el-button>
            </div>
            <div class="tip mt10" style="color: red">
              待支付金额：{{
              orderInfo &&
              Number(orderInfo.payAmount || 0).tranFormat(2, -2, false)
              }}元，请在下单30分钟内完成给支付，剩余时间：
              <el-statistic
                ref="statistic"
                @finish="hilarity"
                format="HH:mm:ss"
                :value="deadline"
                time-indices
              ></el-statistic>
            </div>
          </template>
          <!-- 已支付待派单 -->
          <template slot="extra" v-if="orderInfo && orderInfo.orderStatus == 'WART_SEND'">
            <div style="display: flex; justify-content: flex-end">
              <el-button size="small" type="danger" @click="onRefundClose">退款关闭</el-button>
            </div>
          </template>
          <!-- 已派单待预约 / 已预约，待上门 /施工中-->
          <template
            slot="extra"
            v-if="
              orderInfo &&
              ['WART_APPOINTMENT', 'WART_SITE', 'WORKING'].includes(orderInfo.orderStatus)
            "
          >
            <div
              v-if="orderInfo && orderInfo.extraServiceOrderId"
              style="display: flex; justify-content: flex-end; margin-top: 10px"
            >
              <el-button size="small" type="success" @click="onPayAddPrice">去支付</el-button>
            </div>
            <div
              style="color: red; font-size: 12px; padding-left: 40px"
              v-if="orderInfo && orderInfo.extraOrderAmount"
            >
              {{
              orderInfo && orderInfo.extraOrderAmount | filterPriceFormat
              }}元加价单待支付
            </div>
          </template>
          <!-- 已完工，待验收 -->
          <template slot="extra" v-if="orderInfo && orderInfo.orderStatus == 'WART_CHECK'">
            <div style="display: flex; justify-content: flex-end">
              <el-button size="small" type="success" @click="handleOrderFinish">验收完成</el-button>
              <el-button size="small" type="warning" @click="onSellAfterDialog">发起售后</el-button>
            </div>
          </template>
          <!-- 已验收，订单完成 -->
          <template slot="extra" v-if="orderInfo && orderInfo.orderStatus == 'FINISH'">
            <div style="display: flex; justify-content: flex-end">
              <!-- 商家端有 -->
              <el-button
                size="small"
                type="success"
                @click="onRateDialog"
                v-if="!orderInfo.evaluateResDTO"
              >服务评价</el-button>
              <!-- 商家端有 -->
              <el-button size="small" type="warning" @click="onSellAfterDialog">发起售后</el-button>
            </div>
          </template>
          <el-descriptions-item label="订单号">{{ orderInfo && orderInfo.serviceOrderId }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ orderInfo && orderInfo.createTime }}</el-descriptions-item>
        </el-descriptions>
        <el-tabs type="border-card">
          <el-tab-pane label="订单信息">
            <OrderInfo :orderInfo="orderInfo" :mode="mode" :saasId="saasId" />
          </el-tab-pane>
          <el-tab-pane label="异常信息">暂无</el-tab-pane>
          <el-tab-pane label="服务评价">
            <div v-if="orderInfo && orderInfo.evaluateResDTO">
              <el-descriptions :column="1">
                <el-descriptions-item label="六鸽服务打分">
                  <el-rate :value="orderInfo.evaluateResDTO.mark" disabled></el-rate>
                </el-descriptions-item>
                <el-descriptions-item label="标签">
                  <el-tag
                    :key="tag"
                    v-for="tag in orderInfo.evaluateResDTO.labels.split(',')"
                    style="margin: 0 5px 5px 0"
                  >{{ tag }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="描述">{{ orderInfo.evaluateResDTO.describe }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div v-else>暂无</div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="8">
        <el-descriptions title="师傅信息" :column="1" class="out-border mb10" :colon="false">
          <!-- 已下单待支付 -->
          <el-descriptions-item v-if="orderInfo && orderInfo.workerId">
            <el-row class="row">
              <el-col :span="8">
                <el-avatar class="avatar" :src="orderInfo.workerAvatar"></el-avatar>
              </el-col>
              <el-col :span="16">
                <div class="item">姓名:{{ orderInfo.workerName }}</div>
                <!-- <div class="item">手机号:{{ orderInfo.workerMobile }}</div> -->
                <div class="item">师傅id:{{ orderInfo.workerId }}</div>
              </el-col>
              <el-col :span="24" style="margin-top: 20px">
                <el-timeline>
                  <el-timeline-item
                    v-if="orderInfo.payTime"
                    :timestamp="orderInfo.receiveOrderTime"
                  >支付完成，师傅接到订单</el-timeline-item>
                  <el-timeline-item
                    v-for="item in orderInfo.orderChangeResDTOList"
                    :key="item.createTime"
                    :timestamp="
                      item.changeType === 'UPDATE_APPOINTMENT' ||
                      item.changeType == 'APPOINTMENT'
                        ? `${item.appointmentDate} ${item.appointmentStartTime}-${item.appointmentFinishTime}`
                        : item.createTime
                    "
                  >{{ item.changeType | filterChangeTypeEnum }}</el-timeline-item>
                </el-timeline>
              </el-col>
            </el-row>
          </el-descriptions-item>
          <el-descriptions-item v-else>暂无</el-descriptions-item>
          <!-- 已下单待支付 -->
        </el-descriptions>
      </el-col>
    </el-row>
    <ThePay
      ref="payRefs"
      :dataId="orderInfo && orderInfo.merchantId"
      data-type="MERCHANT"
      @paySuccess="paySuccess"
    />

    <RefundClose ref="refundCloseRefs" :orderInfo="orderInfo" @refundClose="handleRefundClose" />
    <SellAfter
      ref="sellAfterRefs"
      :serviceOrderId="serviceOrderId"
      @sendSellAfter="handleSellAfter"
    />
    <TheRate ref="rateRefs" @onRate="handleRate" />
  </div>
</template>

<script>
import {
  apiOrderBDetail,
  apiOrderBCancelOrder,
  apiOrderBRefundClose,
  apiOrderBEvaluate,
  apiOrderBFinish
} from "@/api/order.js";
import { apiOrderBApplyRefund } from "@/api/salesAfter.js";
import { filterOrderStatus, filterChangeTypeEnum } from "@/filters/index";
import OrderInfo from "./components/orderInfo.vue";
import ThePay from "@/components/ThePay/index.vue";
import RefundClose from "./components/refundClose.vue";
import SellAfter from "./components/sellAfter.vue";
import TheRate from "@/components/TheRateDialog/index.vue";

export default {
  components: {
    SellAfter,
    OrderInfo,
    ThePay,
    RefundClose,
    TheRate
  },
  data() {
    return {
      serviceOrderId: "",
      orderInfo: null,
      deadline: 0,
      filterOrderStatus: filterOrderStatus,
      filterChangeTypeEnum: filterChangeTypeEnum,
      downTime: 0,
      mode: "",
      saasId: "",
      hilarityStop: true
    };
  },
  mounted() {
    try {
      const { serviceOrderId, mode, saasId } = this.$route.query;
      this.serviceOrderId = serviceOrderId;
      this.getData();
    } catch (error) {
      this.$message("丢失主键");
    }
  },
  methods: {
    getData() {
      apiOrderBDetail({ serviceOrderId: this.serviceOrderId }).then(res => {
        if (res.code == "SUCCESS") {
          this.saasId = res.data.saasId;
          this.mode = res.data.saasId == "LiuGe" ? "platform" : "saas";
          this.orderInfo = {
            ...res.data,
            payAmountList: res.data.payAmountList
              ? res.data.payAmountList.split(",").filter(item => item > 0)
              : [],
            commissionAmountList: res.data.commissionAmountList
              ? res.data.commissionAmountList
                  .split(",")
                  .filter(item => item > 0)
              : [],
            saasAmountList: res.data.saasAmountList
              ? res.data.saasAmountList.split(",").filter(item => item > 0)
              : []
          };
          const downTime =
            new Date(res.data.createTime).getTime() +
            30 * 60 * 1000 -
            Date.now();
          console.log(downTime, "downTime");
          this.deadline = Date.now() + (downTime > 0 ? downTime : 0);
          this.hilarityStop = this.downTime <= 0;
        }
      });
    },

    // 支付
    onGoPay() {
      // 显示支付
      const payUtils = {
        payWay: "BALANCE",
        payAmount: this.orderInfo.payAmount,
        mode: "order",
        ext: {
          tradeType: "NATIVE",
          serviceOrderId: this.orderInfo.serviceOrderId
        },
        hilarityTime: this.orderInfo.createTime
      };
      this.$refs.payRefs.onShow(payUtils);
    },
    showAddPriceBtn() {
      if (this.orderInfo.payAmountList.length < 2) {
        if (this.orderInfo && !orderInfo.extraServiceOrderId) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    paySuccess() {
      this.getData();
    },
     // 确认加价，并支付
     handleAddPrice(values) {
      console.log(this.orderInfo);
      apiExtraServiceOrderCreate({
        ...values,
        commissionAmount: values.commissionAmount * 100,
        orderAmount: values.orderAmount * 100,
        serviceOrderId: this.orderInfo.serviceOrderId
      }).then(res => {
        this.$message({ type: "success", message: "创建加价单成功" });
        this.getData();
        const payUtils = {
          payWay: "BALANCE",
          payAmount: res.data.orderAmount,
          mode: "extraOrder",
          ext: {
            tradeType: "NATIVE",
            extraServiceOrderId: res.data.extraServiceOrderId
          },
          hilarityTime: res.data.extraOrderCreateTime
        };
        this.$refs.payRefs.onShow(payUtils);
      });
    },
    // 支付加价单
    onPayAddPrice() {
      const payUtils = {
        payWay: "BALANCE",
        payAmount: this.orderInfo.extraOrderAmount,
        mode: "extraOrder",
        ext: {
          tradeType: "NATIVE",
          extraServiceOrderId: this.orderInfo.extraServiceOrderId
        },
        hilarityTime: this.orderInfo.extraOrderCreateTime
      };
      this.$refs.payRefs.onShow(payUtils);
    },
    // 关闭加价单
    onCloseAddPrice() {
      this.$confirm("确认关闭加价单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        apiExtraServiceOrderBCloseRaise({
          extraServiceOrderId: this.orderInfo.extraServiceOrderId
        }).then(res => {
          if (res.code === "SUCCESS") {
            this.$message({ type: "success", message: "关闭加价单成功" });
            this.getData();
          }
        });
      });
    },
    // 取消订单
    onCancelOrder() {
      this.$confirm("平台正在安排合适的师傅！", "确定取消订单？", {
        confirmButtonText: "取消订单",
        cancelButtonText: "返回",
        type: "warning"
      })
        .then(() => {
          apiOrderBCancelOrder({ serviceOrderId: this.serviceOrderId }).then(
            res => {
              if (res.code == "SUCCESS") {
                this.$message({
                  type: "success",
                  message: "取消订单成功!"
                });
                this.getData();
              }
            }
          );
        })
        .catch(() => {});
    },

    // 退款关闭
    onRefundClose() {
      const { orderStatus, serviceOrderId } = this.orderInfo;
      if (orderStatus == "WART_SEND") {
        this.$confirm("支付款原路返回", "确定退款关闭订单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            apiOrderBRefundClose({
              serviceOrderId
            }).then(res => {
              if (res.code === "SUCCESS") {
                this.$message({ type: "success", message: "退款关闭成功" });
                this.getData();
              }
            });
          })
          .catch(() => {});
      } else {
        this.$refs.refundCloseRefs.onShow();
      }
    },
    // 确认关闭退款单
    handleRefundClose(row) {
      console.log(row);
      apiOrderBRefundClose({
        serviceOrderId: this.orderInfo.serviceOrderId,
        ...row,
        saleAmount: row.saleAmount * 100
      }).then(res => {
        if (res.code === "SUCCESS") {
          this.$message({ type: "success", message: "退款关闭成功" });
          this.getData();
        }
      });
    },
    // 发起售后弹窗
    onSellAfterDialog() {
      this.$refs.sellAfterRefs.onShow();
    },
    handleSellAfter(values) {
      const params = {
        serviceOrderId: this.serviceOrderId,
        afterSaleType: values.afterSaleType, //售后类型
        problem: values.problem, //问题描述
        phone: values.phone, //联系电话
        proof: values.proof.join(",") //证据信息
      };
      apiOrderBApplyRefund({ ...params }).then(res => {
        if (res.code === "SUCCESS") {
          this.$message({ type: "success", message: "发起售后成功" });
          this.getData();
        }
      });
    },
    // 订单验收完成
    handleOrderFinish() {
      this.$confirm("确认验收无误?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          apiOrderBFinish({
            serviceOrderId: this.orderInfo.serviceOrderId
          }).then(res => {
            this.$message({ type: "success", message: "订单验收完成" });
            this.getData();
            this.onRateDialog();
          });
        })
        .catch(() => {});
    },
    onRateDialog() {
      this.$refs.rateRefs.onShow();
    },
    handleRate(e) {
      const { remark, rate, tags } = e;
      const params = {
        serviceOrderId: this.orderInfo.serviceOrderId,
        describe: remark,
        mark: rate,
        labels: tags.join(",")
      };
      apiOrderBEvaluate({ ...params }).then(res => {
        if (res.code === "SUCCESS") {
          this.$message({ type: "success", message: "服务评分成功" });
          this.getData();
        }
      });
    },
    // 支付倒计时结束
    hilarity() {
      if (this.hilarityStop) {
        return false;
      }
      this.getData();
      this.hilarityStop = true;
    }
  }
};
</script>
<style scoped lang="scss">
.tip {
  display: flex;
  ::v-deep .el-statistic {
    width: auto;
    display: inline-block;
    .con {
      color: red !important;
      .number {
        font-size: 16px !important;
        line-height: auto;
      }
    }
  }
}
.row {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .avatar {
    width: 80px;
    height: 80px;
  }
}
</style>
